package com.rbac.admin.controller.system;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rbac.admin.annotation.OperationLog;
import com.rbac.admin.common.result.Result;
import com.rbac.admin.entity.system.SystemRole;
import com.rbac.admin.service.system.RoleService;
import com.rbac.admin.vo.system.RoleVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 角色管理控制器
 *
 * @author rbac-admin
 * @since 2024-05-29
 */
@RestController
@RequestMapping("/system/roles")
@Tag(name = "角色管理", description = "角色管理相关接口")
public class RoleController {

    @Autowired
    private RoleService roleService;

    /**
     * 分页查询角色列表
     */
    @Operation(summary = "分页查询角色列表")
    @OperationLog(module = "角色管理", type = "查询", value = "查询角色列表")
    @GetMapping
    public Result<IPage<RoleVO>> getRoleList(
            @Parameter(description = "当前页码") @RequestParam(defaultValue = "1") long current,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") long size,
            @Parameter(description = "角色名称") @RequestParam(required = false) String roleName,
            @Parameter(description = "角色编码") @RequestParam(required = false) String roleCode,
            @Parameter(description = "状态") @RequestParam(required = false) Integer status) {
        try {
            // 构建查询条件
            SystemRole role = new SystemRole();
            role.setRoleName(roleName);
            role.setRoleCode(roleCode);
            role.setStatus(status);
            
            // 分页查询
            Page<RoleVO> page = new Page<>(current, size);
            IPage<RoleVO> pageResult = roleService.getRolePage(page, role);
            
            return Result.success(pageResult);
        } catch (Exception e) {
            return Result.failed("查询角色列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 查询所有活跃角色（用于下拉选择）
     */
    @Operation(summary = "查询所有活跃角色")
    @GetMapping("/active")
    public Result<List<RoleVO>> getAllActiveRoles() {
        try {
            List<RoleVO> roles = roleService.getAllActiveRoles();
            return Result.success(roles);
        } catch (Exception e) {
            return Result.failed("查询活跃角色失败：" + e.getMessage());
        }
    }

    /**
     * 获取角色详情
     */
    @Operation(summary = "获取角色详情")
    @OperationLog(module = "角色管理", type = "查询", value = "查看角色详情")
    @GetMapping("/{id}")
    public Result<RoleVO> getRoleById(@Parameter(description = "角色ID") @PathVariable int id) {
        try {
            RoleVO role = roleService.getRoleById(String.valueOf(id));
            if (role == null) {
                return Result.failed("角色不存在");
            }
            return Result.success(role);
        } catch (Exception e) {
            return Result.failed("获取角色详情失败：" + e.getMessage());
        }
    }

    /**
     * 创建角色
     */
    @Operation(summary = "创建角色")
    @OperationLog(module = "角色管理", type = "新增", value = "新增角色", recordParams = true, recordResult = true)
    @PostMapping
    public Result<SystemRole> createRole(@RequestBody SystemRole role) {
        try {
            // 检查角色编码是否已存在
            if (roleService.checkRoleCodeExists(role.getRoleCode(), null)) {
                return Result.failed("角色编码已存在");
            }
            
            // 检查角色名称是否已存在
            if (roleService.checkRoleNameExists(role.getRoleName(), null)) {
                return Result.failed("角色名称已存在");
            }
            
            // 设置默认值
            role.setCreateTime(LocalDateTime.now());
            role.setUpdateTime(LocalDateTime.now());
            role.setDeleteFlag(0);
            
            boolean success = roleService.save(role);
            if (success) {
                return Result.success("创建成功", role);
            } else {
                return Result.failed("创建失败");
            }
        } catch (Exception e) {
            return Result.failed("创建角色失败：" + e.getMessage());
        }
    }

    /**
     * 更新角色
     */
    @Operation(summary = "更新角色")
    @OperationLog(module = "角色管理", type = "修改", value = "修改角色信息", recordParams = true, recordResult = true)
    @PutMapping("/{id}")
    public Result<Boolean> updateRole(
            @Parameter(description = "角色ID") @PathVariable int id,
            @RequestBody SystemRole role) {
        try {
            // 检查角色是否存在
            SystemRole existRole = roleService.getById(id);
            if (existRole == null) {
                return Result.failed("角色不存在");
            }
            
            // 检查角色编码是否已存在（排除自身）
            if (roleService.checkRoleCodeExists(role.getRoleCode(), String.valueOf(id))) {
                return Result.failed("角色编码已存在");
            }
            
            // 检查角色名称是否已存在（排除自身）
            if (roleService.checkRoleNameExists(role.getRoleName(), String.valueOf(id))) {
                return Result.failed("角色名称已存在");
            }
            
            // 设置ID和更新时间
            role.setId(id);
            role.setUpdateTime(LocalDateTime.now());
            
            boolean success = roleService.updateById(role);
            if (success) {
                return Result.success("更新成功", true);
            } else {
                return Result.failed("更新失败");
            }
        } catch (Exception e) {
            return Result.failed("更新角色失败：" + e.getMessage());
        }
    }

    /**
     * 删除角色
     */
    @Operation(summary = "删除角色")
    @OperationLog(module = "角色管理", type = "删除", value = "删除角色", recordParams = true)
    @DeleteMapping("/{id}")
    public Result<Boolean> deleteRole(@Parameter(description = "角色ID") @PathVariable int id) {
        try {
            // 检查角色是否存在
            SystemRole role = roleService.getById(id);
            if (role == null) {
                return Result.failed("角色不存在");
            }
            
            // 检查角色是否有关联用户
            if (roleService.hasAssociatedUsers(String.valueOf(id))) {
                return Result.failed("该角色下存在关联用户，无法删除");
            }
            
            // 逻辑删除角色（MyBatis-Plus自动处理）
            boolean success = roleService.removeById(id);
            if (success) {
                return Result.success("删除成功", true);
            } else {
                return Result.failed("删除失败");
            }
        } catch (Exception e) {
            return Result.failed("删除角色失败：" + e.getMessage());
        }
    }

    /**
     * 批量删除角色
     */
    @Operation(summary = "批量删除角色")
    @OperationLog(module = "角色管理", type = "删除", value = "批量删除角色", recordParams = true)
    @DeleteMapping("/batch")
    public Result<Boolean> batchDeleteRoles(@RequestBody Map<String, List<Integer>> params) {
        try {
            List<Integer> ids = params.get("ids");
            if (ids == null || ids.isEmpty()) {
                return Result.failed("角色ID列表不能为空");
            }
            
            // 检查所有角色是否有关联用户
            for (Integer id : ids) {
                if (roleService.hasAssociatedUsers(String.valueOf(id))) {
                    return Result.failed("ID为" + id + "的角色下存在关联用户，无法删除");
                }
            }
            
            // 批量逻辑删除角色（MyBatis-Plus自动处理）
            boolean success = roleService.removeByIds(ids);
            if (success) {
                return Result.success("批量删除成功", true);
            } else {
                return Result.failed("批量删除失败");
            }
        } catch (Exception e) {
            return Result.failed("批量删除角色失败：" + e.getMessage());
        }
    }

    /**
     * 修改角色状态
     */
    @Operation(summary = "修改角色状态")
    @OperationLog(module = "角色管理", type = "修改", value = "修改角色状态", recordParams = true)
    @PutMapping("/{id}/status")
    public Result<Boolean> changeRoleStatus(
            @Parameter(description = "角色ID") @PathVariable int id,
            @RequestBody Map<String, Integer> params) {
        try {
            // 检查角色是否存在
            SystemRole role = roleService.getById(id);
            if (role == null) {
                return Result.failed("角色不存在");
            }
            
            Integer status = params.get("status");
            if (status == null) {
                return Result.failed("状态参数不能为空");
            }
            
            // 修改状态
            role.setStatus(status);
            role.setUpdateTime(LocalDateTime.now());
            
            boolean success = roleService.updateById(role);
            if (success) {
                return Result.success("状态修改成功", true);
            } else {
                return Result.failed("状态修改失败");
            }
        } catch (Exception e) {
            return Result.failed("修改角色状态失败：" + e.getMessage());
        }
    }
} 